import axios from "axios";
// import { getLocalStorage, setLocalStorage } from "@/utils/localstorage.ts";
// import { LocalstorageEnum } from "@/types/localstorage.ts";
import { PubSubEnum } from "@/types";
import PubSub from "pubsub-js";
import { UserStore } from "@/store";
import { encrypt, decrypt } from "@/utils/cryptoService";
import { useRouter } from "vue-router";
import { UserAxios } from "@/api";
import { FiltrationFun } from "@/utils";
import { showToast } from "vant";
import DeviceDetector from "device-detector-js";
import moment from "moment";
const router = useRouter();
const deviceDetector = new DeviceDetector();
const { os } = deviceDetector.parse(navigator.userAgent);
const device = os !== null ? os.name : "";
import i18n from "@/locales/i18n";
const { t } = i18n.global;
declare global {
  interface Window {
    __backend_api_url: string;
    logger: string | number;
  }
}

function getServerUrl() {
  const defaultUrl = import.meta.env.VITE_BACKEND_DOMAIN;
  const inCacheUrl = localStorage.getItem("__backend_api_url");
  const inWindow = window.__backend_api_url;
  return inWindow || inCacheUrl || defaultUrl;
}

const needApiLog = !!localStorage.getItem("__need_api_log");

// 创建axios实例
const Axios = axios.create({
  // TODO: 后端服务器改这里 http://192.168.66.168:1001 http://www.br0011.com:1001,https://game-apitest.br0011.com，"http://192.168.66.112:1001"
  baseURL: getServerUrl(),
  timeout: 5000, // 请求超时时间
});
// request拦截器
Axios.interceptors.request.use(
  async config => {
    const userStore = UserStore();
    //加密
    config.data = !config.data ? {} : config.data;
    const rawData = config.data;
    if (needApiLog) {
      config["debugRequestData"] = rawData;
    }
    if (import.meta.env.MODE !== "development") {
      config.data = {
        param: encrypt(JSON.stringify(config.data)),
      };
    }
    if (userStore.isLogin && userStore.userLoginInfo.token.accessToken !== "") {
      //判断是token是否快要过期
      const expiresIn = userStore.userLoginInfo.token.expiresIn;
      const currentTime = moment().unix(); //当前时间
      if (expiresIn - currentTime <= 300 && expiresIn - currentTime > 0) {
        if (!userStore.getNewToKenType) {
          userStore.setNewToKenType();
          UserAxios.getNewToken({ device: device, deviceId: FiltrationFun.getDeviceId() || "" })
            .then(res => {
              userStore.setNewToken(res);
              userStore.setNewToKenType();
            })
            .catch(() => {
              userStore.setNewToKenType();
            });
        }
      }
    }

    config.headers.TraceId = FiltrationFun.randomizedString() + moment().valueOf();
    const newTokenUrl = "/hall/v1/user/getNewToken";
    config.headers.Authorization =
      newTokenUrl !== config.url
        ? userStore.userLoginInfo.token.accessToken
        : userStore.userLoginInfo.token.refreshToken;
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

// respone拦截器
Axios.interceptors.response.use(
  response => {
    if (needApiLog) {
      console.log(response.config.url, "request ===>", response.config["debugRequestData"]);
      //console.log("有data吗", response.data);
    }
    const res = response.data;
    const { code } = res;
    const userStore = UserStore();
    if (code !== 200) {
      if (code === 1001) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.systemError"),
        // });
        //系统错误
        showToast(t("responseTip.systemError"));
      } else if (code === 1002) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.ParameterType"),
        // });
        //参数类型错误
        showToast(t("responseTip.ParameterType"));
      } else if (code === 1003) {
        //token失效重新获取新的token
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: "因网络问题，请重新尝试" + msg,
        // });
        if (userStore.isLogin && userStore.userLoginInfo.token.accessToken !== "") {
          if (userStore.getNewToKenType) {
            userStore.setNewToKenType();
          }
          if (!userStore.getNewToKenType) {
            userStore.setNewToKenType();
            UserAxios.getNewToken({ device: device, deviceId: FiltrationFun.getDeviceId() || "" })
              .then(res => {
                userStore.setNewToKenType();
                userStore.setNewToken(res);
              })
              .catch(() => {
                userStore.setNewToKenType();
              });
          }
        }
      } else if (code === 1004) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.TokenGenerationFail"),
        // });
        //token生成失败
        showToast(t("responseTip.TokenGenerationFail"));
      } else if (code === 1005) {
        //游戏服务繁忙,请重试
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.GameServiceIsBusyPleaseTryAgain"),
        // });
        showToast(t("responseTip.GameServiceIsBusyPleaseTryAgain"));
      } else if (code === 1006) {
        //用户余额不足
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.GameServiceIsBusyPleaseTryAgain"),
        // });
        showToast(t("responseTip.code1006"));
      } else if (code === 1009) {
        //账号被封禁
        PubSub.publish(PubSubEnum.DEACTIVATE_TOAST);
      } else if (code === 1010) {
        //系统维护状态
        const path = router.currentRoute.value.path;
        if (!path.includes("safeguardPage")) {
          router.push("safeguardPage");
        }
      } else if (code === 1014) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: "请先登录",
        // });
        userStore.resetUserConfig();
        userStore.$reset();
      } else if (code === 1103) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.ipRestrict"),
        // });
        //ip受限
        showToast(t("responseTip.ipRestrict"));
      } else if (code === 2001) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.accountYouEnteredDoesNotExist"),
        // });
        //您输入的账号不存在
        showToast(t("responseTip.accountYouEnteredDoesNotExist"));
      } else if (code === 2002) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.accountPasswordErr"),
        // });
        //账号或密码错误
        showToast(t("responseTip.accountPasswordErr"));
      } else if (code === 2003) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.userAlreadyExistsPleaseReenter"),
        // });
        //用户已存在，请重新输入
        showToast(t("responseTip.userAlreadyExistsPleaseReenter"));
      } else if (code === 2004) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.userAgentDoesNotExist"),
        // });
        //用户代理不存在
        showToast(t("responseTip.userAgentDoesNotExist"));
      } else if (code === 2011) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.NoWithdrawalsAllow"),
        // });
        //充值金额大于最大值，不让提现
        showToast(t("responseTip.NoWithdrawalsAllow"));
      } else if (code === 3001) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: "用户VIP等级不足无法领取",
        // });
        showToast(t("responseTip.code3001"));
      } else if (code === 3002) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.usersVIPRewardHasAlreadyBeenClaim"),
        // });
        //用户vip奖励已领取
        showToast(t("responseTip.usersVIPRewardHasAlreadyBeenClaim"));
      } else if (code === 3003) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.WithoutAnyTransactionRecords"),
        // });
        //用户昨天没有任何交易记录，无法领取
        showToast(t("responseTip.WithoutAnyTransactionRecords"));
      } else if (code === 3004) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.userDoesNotHaveEnoughFundsToClaimIt"),
        // });
        //用户没有足够的流水来领取
        showToast(t("responseTip.userDoesNotHaveEnoughFundsToClaimIt"));
      } else if (code === 3005) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.insufficientNumberPeople"),
        // });
        //人数不足
        showToast(t("responseTip.insufficientNumberPeople"));
      } else if (code === 3006) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.repeatClaim"),
        // });
        //重复领取
        showToast(t("responseTip.repeatClaim"));
      } else if (code === 3008) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.insufficientWaterFlow"),
        // });
        //流水不足
        showToast(t("responseTip.insufficientWaterFlow"));
      } else if (code === 3011) {
        //红包雨活动未开启
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.redEnvelopeRainActivityNotActivat"),
        // });
        showToast(t("responseTip.redEnvelopeRainActivityNotActivat"));
      } else if (code === 3012) {
        //红包雨活动时间未到
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.TimeHasNotArrivedYet"),
        // });
        showToast(t("responseTip.TimeHasNotArrivedYet"));
      } else if (code === 3013) {
        //红包雨达到最大限值
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.redEnvelopeRainReachesMaximumLimitValue"),
        // });
        showToast(t("responseTip.redEnvelopeRainReachesMaximumLimitValue"));
      } else if (code === 3014) {
        //当前时间段内已领取
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.TreceivedDuringCurrentTimePeriod"),
        // });
        showToast(t("responseTip.TreceivedDuringCurrentTimePeriod"));
      } else if (code === 3021) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   //红包雨今日未充值,无法领取
        //   text: t("responseTip.TodayCannotBeClaim"),
        // });
        showToast(t("responseTip.TodayCannotBeClaim"));
      } else if (code === 3022) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.levelActivityNotActivat"),
        // });
        //等级活动未开启
        showToast(t("responseTip.levelActivityNotActivat"));
      } else if (code === 3023) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.levelActivityHasBeenClaim"),
        // });
        //等级活动已领取
        showToast(t("responseTip.levelActivityHasBeenClaim"));
      } else if (code === 3024) {
        // PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
        //   text: t("responseTip.levelActivityCollectionFail"),
        // });
        //等级活动领取失败
        showToast(t("responseTip.levelActivityCollectionFail"));
      }
      return Promise.reject(res);
    }
    const getData = import.meta.env.MODE !== "development" ? decrypt(res.data) : res.data;
    const rawData = JSON.parse(getData);
    if (needApiLog) {
      console.log("responese ===>", rawData);
      const url = response.config.url;
      const requestData = response.config["debugRequestData"];
      console.groupCollapsed(url);
      console.log(`请求参数：${JSON.stringify(requestData, null, 2)}`);
      console.log(`返回结果：${JSON.stringify(rawData, null, 2)}`);
      console.groupEnd();
    }
    if (code === 200) {
      return rawData;
    }
    return Promise.reject(res);
  },
  error => {
    PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
      text: t("responseTip.unableToConnectToSystem"),
    });
    return Promise.reject(error);
  },
);

export default Axios;
